<template>
  <van-nav-bar
    left-text="返回"
    left-arrow
    @click-left="$router.back()"
    title="修改密码"
    placeholder
    fixed
  >
    <template #right>
      <van-button text type="primary" size="small" @click="onSubmit">修改</van-button>
    </template>
  </van-nav-bar>

  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="oldPassword"
        name="oldPassword"
        label="旧密码"
        placeholder="旧密码"
        :rules="[{ required: true, message: '请填写旧密码' }]"
      />
      <van-field
        v-model="newPassword"
        type="password"
        name="newPassword"
        label="新密码"
        placeholder="新密码"
        :rules="[{ required: true, message: '请填写新密码' }]"
      />
      <van-field
        v-model="confirmPassword"
        type="password"
        name="confirmPassword"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '请填写确认密码' }]"
      />
    </van-cell-group>
  </van-form>
</template>

<script setup>
import { ref } from 'vue'
import { getUserInfoReq, userUpdatePwdReq } from '@/api/user'
import { useRouter } from 'vue-router'

let userInfo = ref({})
// 获取用户信息
function getUserInfo() {
  getUserInfoReq().then((res) => {
    // console.log(res.data.data)
    userInfo.value = res.data.data
    oldPasswordTrue.value = res.data.data.password
  })
}
getUserInfo()
// 修改昵称
let oldPasswordTrue = ref('')
let oldPassword = ref('')
let newPassword = ref('')
let confirmPassword = ref('')

function validateForm() {
  if (oldPassword.value !== oldPasswordTrue.value) {
    // eslint-disable-next-line no-undef
    showFailToast('旧密码错误')
    return false
  } else {
    if (newPassword.value !== confirmPassword.value) {
      // eslint-disable-next-line no-undef
      showFailToast('新密码和确认密码不一致')
      return false
    }
    return true
  }
}

let router = useRouter()
function onSubmit() {
  if (validateForm()) {
    userUpdatePwdReq(newPassword.value,oldPassword.value ).then((res) => {
      // console.log(res.data)

      if (res.data.code === 1) {
        // eslint-disable-next-line no-undef
        showSuccessToast('密码修改成功')
        localStorage.removeItem('mall-token')
        router.push('/login')
      } else {
        // eslint-disable-next-line no-undef
        showFailToast(res.data.msg)
      }
    })
  }
}
</script>

<style scoped></style>
